const express = require('express');
const router = express.Router();
const { pool } = require('../config/database');

// 获取优惠券列表
router.get('/list', async (req, res) => {
  try {
    const { page = 1, limit = 10, publish_status } = req.query;
    const offset = (page - 1) * limit;
    
    let whereClause = 'WHERE is_deleted = 0';
    let params = [];
    
    if (publish_status !== undefined) {
      whereClause += ' AND publish_status = ?';
      params.push(publish_status);
    }
    
    const [coupons] = await pool.execute(
      `SELECT * FROM coupon_info ${whereClause} ORDER BY create_time DESC LIMIT ? OFFSET ?`,
      [...params, parseInt(limit), parseInt(offset)]
    );
    
    const [countResult] = await pool.execute(
      `SELECT COUNT(*) as total FROM coupon_info ${whereClause}`,
      params
    );
    
    res.json({
      success: true,
      message: '获取优惠券列表成功',
      data: {
        list: coupons,
        total: countResult[0].total,
        page: parseInt(page),
        limit: parseInt(limit)
      }
    });
  } catch (error) {
    console.error('获取优惠券列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取优惠券列表失败',
      error: error.message
    });
  }
});

// 根据ID获取优惠券
router.get('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const [rows] = await pool.execute(
      'SELECT * FROM coupon_info WHERE id = ? AND is_deleted = 0',
      [id]
    );
    
    if (rows.length === 0) {
      return res.status(404).json({
        success: false,
        message: '优惠券不存在'
      });
    }
    
    res.json({
      success: true,
      message: '获取优惠券信息成功',
      data: rows[0]
    });
  } catch (error) {
    console.error('获取优惠券信息失败:', error);
    res.status(500).json({
      success: false,
      message: '获取优惠券信息失败',
      error: error.message
    });
  }
});

// 添加优惠券
router.post('/add', async (req, res) => {
  try {
    const {
      coupon_type,
      coupon_name,
      amount,
      condition_amount,
      start_time,
      end_time,
      range_type,
      range_desc,
      publish_count,
      per_limit,
      expire_time,
      publish_status
    } = req.body;
    
    if (!coupon_name || !amount) {
      return res.status(400).json({
        success: false,
        message: '优惠券名称和金额不能为空'
      });
    }
    
    const [result] = await pool.execute(
      `INSERT INTO coupon_info (
        coupon_type, coupon_name, amount, condition_amount, start_time, end_time,
        range_type, range_desc, publish_count, per_limit, expire_time, publish_status
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
      [
        coupon_type || 1,
        coupon_name,
        amount,
        condition_amount || 0,
        start_time,
        end_time,
        range_type || 1,
        range_desc,
        publish_count || 1,
        per_limit || 1,
        expire_time,
        publish_status || 0
      ]
    );
    
    res.json({
      success: true,
      message: '添加优惠券成功',
      data: {
        id: result.insertId,
        coupon_name,
        amount
      }
    });
  } catch (error) {
    console.error('添加优惠券失败:', error);
    res.status(500).json({
      success: false,
      message: '添加优惠券失败',
      error: error.message
    });
  }
});

// 更新优惠券
router.put('/update/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const {
      coupon_type,
      coupon_name,
      amount,
      condition_amount,
      start_time,
      end_time,
      range_type,
      range_desc,
      publish_count,
      per_limit,
      expire_time,
      publish_status
    } = req.body;
    
    const [existingCoupon] = await pool.execute(
      'SELECT * FROM coupon_info WHERE id = ? AND is_deleted = 0',
      [id]
    );
    
    if (existingCoupon.length === 0) {
      return res.status(404).json({
        success: false,
        message: '优惠券不存在'
      });
    }
    
    await pool.execute(
      `UPDATE coupon_info SET 
        coupon_type = ?, coupon_name = ?, amount = ?, condition_amount = ?, 
        start_time = ?, end_time = ?, range_type = ?, range_desc = ?, 
        publish_count = ?, per_limit = ?, expire_time = ?, publish_status = ?
      WHERE id = ?`,
      [
        coupon_type,
        coupon_name,
        amount,
        condition_amount,
        start_time,
        end_time,
        range_type,
        range_desc,
        publish_count,
        per_limit,
        expire_time,
        publish_status,
        id
      ]
    );
    
    res.json({
      success: true,
      message: '更新优惠券成功'
    });
  } catch (error) {
    console.error('更新优惠券失败:', error);
    res.status(500).json({
      success: false,
      message: '更新优惠券失败',
      error: error.message
    });
  }
});

// 删除优惠券（软删除）
router.delete('/delete/:id', async (req, res) => {
  try {
    const { id } = req.params;
    
    const [existingCoupon] = await pool.execute(
      'SELECT * FROM coupon_info WHERE id = ? AND is_deleted = 0',
      [id]
    );
    
    if (existingCoupon.length === 0) {
      return res.status(404).json({
        success: false,
        message: '优惠券不存在'
      });
    }
    
    await pool.execute(
      'UPDATE coupon_info SET is_deleted = 1 WHERE id = ?',
      [id]
    );
    
    res.json({
      success: true,
      message: '删除优惠券成功'
    });
  } catch (error) {
    console.error('删除优惠券失败:', error);
    res.status(500).json({
      success: false,
      message: '删除优惠券失败',
      error: error.message
    });
  }
});

// 发布优惠券
router.put('/publish/:id', async (req, res) => {
  try {
    const { id } = req.params;
    
    const [existingCoupon] = await pool.execute(
      'SELECT * FROM coupon_info WHERE id = ? AND is_deleted = 0',
      [id]
    );
    
    if (existingCoupon.length === 0) {
      return res.status(404).json({
        success: false,
        message: '优惠券不存在'
      });
    }
    
    await pool.execute(
      'UPDATE coupon_info SET publish_status = 1 WHERE id = ?',
      [id]
    );
    
    res.json({
      success: true,
      message: '发布优惠券成功'
    });
  } catch (error) {
    console.error('发布优惠券失败:', error);
    res.status(500).json({
      success: false,
      message: '发布优惠券失败',
      error: error.message
    });
  }
});

module.exports = router;